package utils

import (
	"fmt"
	"github.com/fatih/structs"
	"github.com/labstack/echo"
	"os"
)

// FileExists check file is exist
func FileExists(name string) bool {
	_, err := os.Stat(name)
	if os.IsNotExist(err) {
		return false
	}
	ExitOnErr(err)
	return true
}

// ExitOnErr exit the problem if e is not nil
func ExitOnErr(e error) {
	if e != nil {
		fmt.Println(e)
		os.Exit(1)
	}
}

func BindAndValidate(ctx echo.Context, obj interface{}) error {
	if err := ctx.Bind(obj); err != nil {
		return err
	}
	if err := ctx.Validate(obj); err != nil {
		return err
	}
	return nil
}

func PartialUpdate(target interface{}, from interface{}, excludeFields ...string) {
	var findInSlice = func(a []string, s string) bool {
		for _, v := range a {
			if v == s {
				return true
			}
		}
		return false
	}
	data := structs.Map(from)
	targetStruct := structs.New(target)
	for k, v := range data {
		if findInSlice(excludeFields, k) {
			continue
		}
		field, ok := targetStruct.FieldOk(k)
		if !ok || field.Set(v) != nil {
			continue
		}
	}
}

//
//func GetStructValueList(querySet []interface{}, fieldName string) []string {
//	result := make([]string, 0)
//	for _, obj := range querySet {
//		s := structs.New(obj)
//		if field, ok := s.FieldOk(fieldName); !ok {
//			continue
//		} else {
//			result = append(result, field.Value())
//		}
//	}
//}
